<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php
require_once('php_shared/session_to_db.php');

// Self username
$username = "";
// Self user_id in db
$uid = "";
// Mysql query result for friends sql
$friends;
// User_ids of users with currently active sessions
$active_uids = array();
// Mysql query result of friend requests awaiting for response from current user, if there are any
$friend_requests;

session_start();

if( isset($_SESSION['user_id']) )
{
	if( ($_SESSION['user_id'] == null) || ($_SESSION['user_id'] == '') )
	{
		header("Location: login.php");
	}else{
		$db_man = new DbUtils();
			
		if( $db_man->connect() )
		{
			//Get self user_id and username
			$uid = $db_man->set_var($_SESSION['user_id']);
			$sql = "SELECT * FROM registered_user WHERE id=$uid";
			$result = $db_man->query($sql);
			
			if( !$result )
			{
				header("Location: login.php");
			}
			elseif( mysql_num_rows($result) == 1 )
			{
				$row = mysql_fetch_assoc($result);
				$username = $row['username'];
				
				// Get a list of friends
				$sql = "SELECT r.username, r.id FROM friend f, registered_user r WHERE (f.user_id=$uid AND f.friend_id=r.id) OR (f.friend_id=$uid AND f.accepted='1' AND f.user_id=r.id)";
				$friends = $db_man->query($sql);
				
				// Get list of friend requests
				$sql = "SELECT r.username, r.id FROM friend f, registered_user r WHERE (f.user_id=$uid AND f.accepted='0' AND f.friend_id=r.id)";
				$friend_requests = $db_man->query($sql);
				
				// Save current session for later use
				$self_SID = session_id();
				session_write_close();
				// Inspect all session data in database and get a list of active user's user_ids 
				$active_uids = get_active_users($db_man, $uid);
				// Restore original self session
				session_id($self_SID);
				session_start();
			}
		}else{
			header("Location: login.php");
		}
	}
}else{
	header("Location: login.php");
}

function get_active_users( $db_manager, $self_uid )
{
	$sql = "SELECT vchName, uxtExpires FROM tblSession";
	$result = $db_manager->query($sql);
	
	if( !$result )
	{
		return null;
	}else{
		$active_users = array();
		$disturbed_SIDs = array();
		
		while( $row = mysql_fetch_assoc($result) )
		{
			array_push( $disturbed_SIDs, $row );
			session_id( $row['vchName'] );
			session_start();
			
			if( isset( $_SESSION['user_id'] ) )
			{
				if( ($_SESSION['user_id'] != '') && ($_SESSION['user_id'] != $self_uid) )
				{
					array_push( $active_users, $_SESSION['user_id'] );
				}
			}
			
			session_write_close();
		}
		
		// Since we disturbed the expire time of the sessions
		// while we were iterating through them,
		// let's set their expire times back to the original
		foreach( $disturbed_SIDs as $row )
		{
			$name = $db_manager->set_var( $row['vchName'] );
			$old_expire = $db_manager->set_var( $row['uxtExpires'] );
			$sql = "UPDATE tblSession SET uxtExpires=$old_expire WHERE vchName=$name";
			$db_manager->query($sql);
		}
		
		return $active_users;
	}
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Friends List | CSE315 IM</title>
    <link href="css/shared.css" rel="stylesheet" type="text/css" />
    <link href="css/messenger.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/messenger.js"></script>
    <script type="text/javascript" src="js/refresh_timer.js"></script>
</head>

<body onload="JavaScript:auto_refresh();">
	
<div id="container">
        <b class="border1"></b><b class="border2"></b><b class="border3"></b><b class="border4"></b>
		<div class="bordercontent">
            
            <img src="img/CSE315IM_logo.png" width="317" height="79" alt="CSE315 IM Logo" />
       		<br />
            <h3 class="page_title">Friends List</h3>
            <br />
            
            <div class="userbar">
                <label name="username">Logged in as <b><?php print $username; ?></b></label><br />
                <a href="JavaScript:stop_refresh();show_prompt('add_friend_prompt');" class="usercontrol"><img src="img/addfriend.png" alt="Add new friend" /></a>
                <a href="logout.php" class="usercontrol"><img src="img/logout.png" alt="Log out" /></a>
            </div><!-- end #userbar -->
            
            <br />
            
            <table width="100%">
            <tbody>
                	<?php
					/* Construct the friends html table */
					
					if( !$friends )
					{
						print "";
					}else{
						while( $row = mysql_fetch_assoc($friends) )
						{
							$fuid = $row['id'];
							$sql = "SELECT * FROM conversation WHERE (from_uid='$fuid' AND to_uid='$uid' AND isread='0')";
							$result = $db_man->query($sql);
							
							print "<tr>";
							
							/* New message column */
							if( !$result )
							{
								print "<td></td>";
							}
							elseif( mysql_num_rows($result) > 0 )
							{
								print "<td><a href='JavaScript:start_conv(\"".$row['id']."&show_unread=1\");'><img src='img/unread_msg.png' alt='You have unread messages from this user.' /></a></td>";
							}
							else
							{
								print "<td></td>";
							}
							
							/* User status and name column */
							if( in_array($row['id'], $active_uids) )
							{
								print "<td><img src='img/user_online.png' /></td><td>".$row['username']." (online)</td>";
							}else{
								print "<td><img src='img/user_offline.png' /></td><td>".$row['username']." (offline)</td>";
							}
							
							/* Start conversation column */
							print "<td><a href='JavaScript:start_conv(\"".$row['id']."\");'><img src='img/convu.png' alt='Start conversation' /></a></td>";
							
							/* Show-log column */
							print "<td><a href='JavaScript:show_log(\"".$row['id']."\");'><img src='img/log.png' alt='Show logs' /></a></td>";
							
							/* Delete friend column */
							print "<td><a href='JavaScript:stop_refresh();";
							print "document.getElementById(\"del_fid\").value=\"".$row['id']."\";";
							print "document.getElementById(\"del_friendname\").innerText=\"".$row['username']."\";show_prompt(\"del_friend_prompt\");'>";
							print "<img src='img/trash.png' alt='Delete from friend list'/></a></td>";
							
							print "</tr>";
						}
					}
					?>
             </tbody>
          </table>
  		</div><!-- end #bordercontent -->
	    <b class="border4"></b><b class="border3"></b><b class="border2"></b><b class="border1"></b>
        
        <div class="prompt" <?php
        	if( (!$friend_requests) || (mysql_num_rows($friend_requests) == 0) )
			{
				print "style='display: none;'";
			}else{
				print "style='display: block;'";
			}
			?> >
            <b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b>
                <div class="prompt_header">
                    <h3>You have a new friend request!</h3>
                </div><!-- end #prompt_header -->
                <div class="prompt_content">
                	<div class="prompt_icon">
                    	<img src="img/friend_request.png" />
					</div><!-- end #prompt_icon -->
					<div class="prompt_msg">
                   	<?php 
						$row = mysql_fetch_assoc($friend_requests);
						print $row['username'];
					?> wants to be your friend, do you accept the request?
					</div><!-- end #prompt_msg -->
                    <div class="prompt_buttons">
                    	<a href=<?php
							print "'accept_friend_request.php?friend_id=".$row['id']."'";
						?> >
	                    	<img src="img/yes.png" />
                        </a>
                        <a href=<?php
							print "'decline_friend_request.php?friend_id=".$row['id']."'";
						?> >
	                    	<img src="img/no.png" />
                        </a>
                    </div><!-- end #prompt_buttons -->
                </div><!-- end #prompt_content -->
            <b class="b4bh"></b><b class="b3bh"></b><b class="b2bh"></b><b class="b1h"></b>
		</div><!-- end #prompt -->
        
        <div class="prompt" id="add_friend_prompt" style="display: none;" >
            <b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b>
				<div class="prompt_header">
                    <h3>Add a new friend</h3>
                </div><!-- end #prompt_header -->
                <div class="prompt_content">
					<div class="prompt_icon">
                    	<img src="img/friend_request.png" />
 					</div><!-- end #prompt_icon -->
              		<div class="prompt_msg">
						Username of the person you want to add as friend:
                        <input type="text" size="25" maxlength="20" name="new_friend_name" id="new_friend_name" />
                    </div><!-- end #prompt_msg -->
                    <div class="prompt_buttons">
                    	<a href="JavaScript:href_add_friend();" ><img src="img/yes.png" /></a>
                        <a href="JavaScript:hide_prompt('add_friend_prompt');auto_refresh();" ><img src="img/no.png" /></a>
                    </div><!-- end #prompt_buttons -->
                </div><!-- end #prompt_content -->
            <b class="b4bh"></b><b class="b3bh"></b><b class="b2bh"></b><b class="b1h"></b>
		</div><!-- end #prompt -->
        
        <div class="prompt" id="del_friend_prompt" style="display: none;" >
            <b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b>
				<div class="prompt_header">
                    <h3>Delete friend</h3>
                </div><!-- end #prompt_header -->
                <div class="prompt_content">
					<div class="prompt_icon">
                    	<img src="img/trash_big.png" />
 					</div><!-- end #prompt_icon -->
              		<div class="prompt_msg">
						Are you sure you want to delete <label id="del_friendname"></label> from your friend list?
                        <input type="hidden" id="del_fid" value=""  />
                    </div><!-- end #prompt_msg -->
                    <div class="prompt_buttons">
                    	<a href="JavaScript:href_del_friend();" ><img src="img/yes.png" /></a>
                        <a href="JavaScript:hide_prompt('del_friend_prompt');auto_refresh();" ><img src="img/no.png" /></a>
                    </div><!-- end #prompt_buttons -->
                </div><!-- end #prompt_content -->
            <b class="b4bh"></b><b class="b3bh"></b><b class="b2bh"></b><b class="b1h"></b>
		</div><!-- end #prompt -->
        
    </div><!-- end #container -->
    
</body>
</html>